const { Service } = require('egg');


class HomeService extends Service {

  async readyConfig(ctx) {
    try {
      const config = {
        method: ctx.method,
        headers: {},
        data: ctx.request.body,
        params: ctx.query,
        timeout: 200000,
      };


      if (ctx.headers.access_token) {
        config.headers.access_token = ctx.headers.access_token;
      }

      if (ctx.headers.refresh_token) {
        config.headers.refresh_token = ctx.headers.refresh_token;
      }

      const list = ctx.url.split('/');
      const key = await this.app.redis.get(`init:${list[1]}`);

      config.baseURL = `http://${this.app.config.baseIp}:${key}`;
      config.url = ctx.path;

      return config;
    } catch (error) {
      throw error;
    }
  }


  async historyConfig(ctx) {
    const app = this.app;
    try {
      const method = ctx.method.toUpperCase();
      const list = ctx.url.split('/');
      const model = list[1].toUpperCase();
      const ip = ctx.ip;
      let param;

      const data = {
        method, model, ip,
        url: ctx.url,
      };
      if (method === 'GET') {
        param = ctx.query;
      } else {
        param = ctx.request.body;
      }

      const port = await this.app.redis.get('init:history');

      data.param = param;
      const config = {
        method: 'POST',
        baseURL: `http://${this.app.config.baseIp}:${port}`,
        headers: {},
        url: app.config.history,
        data,
        timeout: 200000,
      };

      return config;
    } catch (error) {
      throw error;
    }
  }
}

module.exports = HomeService;
